package com.loto.insurance.framework.Air.BDFZ;

import java.rmi.RemoteException;
import java.text.MessageFormat;

import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;

import java.util.Calendar;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.loto.insurance.framework.InsuranceStatusEnum;
import com.loto.insurance.framework.MsgStatusEnum;
import com.loto.insurance.framework.Air.InsAir;
import com.loto.insurance.framework.Air.InsReturnMsg;
import com.loto.insurance.framework.Air.OrderItemInfo;
import com.loto.insurance.framework.Air.BDFZ.Svl_tansferPolicyDataServiceStub.CancelPolicy;
import com.loto.insurance.framework.Air.BDFZ.Svl_tansferPolicyDataServiceStub.CancelPolicyResponse;
import com.loto.insurance.framework.Air.BDFZ.Svl_tansferPolicyDataServiceStub.TansferpolicyData;
import com.loto.insurance.framework.Air.BDFZ.Svl_tansferPolicyDataServiceStub.TansferpolicyDataResponse;
import com.loto.insurance.framework.Air.PICC.PICCInsAir;
import com.loto.insurance.framework.config.BDFZConfigAir;
import com.loto.insurance.framework.config.ConfigManagementAir;
import com.loto.utils.DateUtils;
import com.loto.utils.XML;

public class BDFZInsAir implements InsAir {
  static Logger logger = LogManager.getLogger(PICCInsAir.class);

  private String productCode;

  private BDFZConfigAir bdfzConfigAir;

  public BDFZInsAir(String productCode) {
	this.productCode = productCode;
	this.bdfzConfigAir = getBdfzConfigAir();
  }

  @Override
  public InsReturnMsg PolicyApproval(OrderItemInfo info) {
	InsReturnMsg message = new InsReturnMsg();
	Calendar now = Calendar.getInstance();

	String request = "<?xml version='1.0' encoding='utf-8'?>"
	    + "<!--10位唯一号码 此现在填的为原来卡单的对方生成规则，需要修改为他们的生成规则，要确保10位号码唯一-->"
	    + "<POLICY ID='##POLICY##'>"
	    + "<!--生效日-->"
	    + "<ISSUEDATE>##ISSUEDATE##</ISSUEDATE>"
	    + "<!--终止日-->"
	    + "<MATURDATE>##MATURDATE##</MATURDATE>"
	    + "<!--保单类型，渠道 现在的类型的流程和网销卡单一样-->"
	    + "<APPSRC>EBUS</APPSRC>"
	    + "<!--单证类型 航意险需要新的单证类型 如果继续编的话就是12-->"
	    + "<APPDOCID>12</APPDOCID>"
	    + "<!--保单申请日-->"
	    + "<APPDATE>##APPDATE##</APPDATE>"
	    + "<!--代理人编号-->"
	    + "<AGENTID>##AGENTID##</AGENTID>"
	    + "<!--回溯日-->"
	    + "<BACKDATE/>"
	    + "<!--保费过期未付选择见代码表-->"
	    + "<NFOOPTION>4</NFOOPTION>"
	    + "<!--支付方式-->"
	    + "<PAYTYPE>G</PAYTYPE>"
	    + "<!--保单人员信息 可多个 ID表示Person的个数顺序，relid表示和被保人关系，relid见附件代码表，1为本人，代表被保人-->"
	    + "##PERSON##" + "<!--险种信息 可多个 ID 1为主险，其余按顺序编-->" + "##PLAN##"
	    + "<!--对应的投保人(xml中person的id )-->" + "<OWNERID>##OWNERID##</OWNERID>"
	    + "<!--对应的付款人(xml中person的id )-->" + "<PAYORID>##OWNERID##</PAYORID>"
	    + "    <!--总保费 以上险种保费总和-->" + "<PREMIUM>##PREMIUM##</PREMIUM>"
	    + "<!--受益人信息 BENEFID-对应的受益人ID（xml person id）RELID见附件代码表-->"
	    + "<BENEF BENEFID='##OWNERID##' RELID='2' SHARE='100' />"
	    + "<!--缴费方式  PAYOPTION见附表-->" + "<PAYOPTION>12</PAYOPTION>"
	    + "<!--APPDOCID 等于上面的APPDOCID -->" + "<CHECKSUM APPDOCID='11'>"
	    + "<!-- 固定值为1 -->" + "<TOTPOLICY>1</TOTPOLICY>"
	    + "<!--等于 PREMIUM 的值-->" + "<TOTPREMIUM>##PREMIUM##</TOTPREMIUM>"
	    + "</CHECKSUM>" + "</POLICY>";
	String person = "<PERSON ID=''{0}'' RELID=''{1}''>" + "<!--EMAIL-->"
	    + "<EMAIL>{2}</EMAIL>" + "<!--地区 中文标示 如 上海上海市  最大18位（转成全角后MAX=18）-->"
	    + "<LOCAL></LOCAL>" + "<!--姓  （转成全角后MAX=22）-->"
	    + "<LASTNAME>{3}</LASTNAME>" + "<!--名  （转成全角后MAX=22）-->"
	    + "<FIRSTNAME>{4}</FIRSTNAME>" + "<!--全名    （转成全角后MAX=44）-->"
	    + "<FULLNAME>{5}</FULLNAME>" + "<!--生日-->"
	    + "<BIRTHDATE>{6}</BIRTHDATE>" + "<!--地址 如XX弄XX号 (转成全角后MAX=68)-->"
	    + "<ADDRESS/>" + "<!--邮编-->" + "<POST/>" + "<!--公司电话  (MAX=12)-->"
	    + "<BUSPHONE/>" + "<RESPHONE/>" + "<!--手机  (MAX=20)-->"
	    + "<CELLPHONE>{7}</CELLPHONE>" + "<!--职业代码-->" + "<PROF>A01</PROF>"
	    + "<!--证件类型-->" + "<SSNTYPE>{8}</SSNTYPE>" + "<!--性别-->"
	    + "<GENDER>{9}</GENDER>" + "<!--证件号码-->" + "<SSNCODE>{10}</SSNCODE>"
	    + "<!--证件有效期-->" + "<SSNEFFECTIVEDATE/>" + "</PERSON>";

	String plan = "<PLAN ID='1'>" + "<!--保费-->" + "<COPREMIUM>{0}</COPREMIUM>"
	    + "<!--险种代码-->" + "<PLANCODE>{1}</PLANCODE>" + "<!--保额-->"
	    + "<FACEAMOUNT>{2}</FACEAMOUNT>" + "<!--期限-->"
	    + "<INSUREDYEARS>{3}</INSUREDYEARS>" + "<!--对应的被保人 (xml中person的id )-->"
	    + "<INSUREDID>1</INSUREDID>" + "</PLAN>";

	request = request.replace("##POLICY##", info.getTransOrderNo());
	request = request.replace("##ISSUEDATE##",
	    DateUtils.dateToString(info.getFromPeriod(), "yyyyMMdd"));
	request = request.replace("##MATURDATE##", DateUtils.dateToString(
	    DateUtils.addDays(info.getFromPeriod(), bdfzConfigAir.getCycle()),
	    "yyyyMMdd"));
	request = request.replace("##APPDATE##",
	    DateUtils.dateToString(now.getTime(), "yyyyMMdd"));
	request = request.replace("##AGENTID##", bdfzConfigAir.getAgentId());
	request = request.replace("##PREMIUM##", bdfzConfigAir.getPremium());

	String[] arrPlans = bdfzConfigAir.getPlan().split("|");
	String plans = "";
	for (String p : arrPlans) {
	  String[] planDetail = p.split("^");
	  if (planDetail.length == 4) {
		plans += MessageFormat.format(plan, planDetail[0], planDetail[1],
		    planDetail[2], planDetail[3]);
	  }
	}
	request = request.replace("##PLAN##", plans);

	String ownerId = "1";
	String persons = "";
	if (info.getInsuredName() == info.getHolderName())// 本人
	{
	  String[] partName = getPartName(info.getInsuredName());
	  persons = MessageFormat.format(person, "1", "1", info.getInsuredEmail(),
		  partName[0], partName[1], info.getInsuredName(),
		  DateUtils.dateToString(info.getInsuredBirth(), "yyyyMMdd"),
		  info.getInsuredTel(), getGender(info.getInsuredGender()),
		  getCertificateType(info.getInsuredCredentialType()),
		  info.getInsuredCredentialNo());
	} else {
	  String[] partName = getPartName(info.getInsuredName());
	  persons = MessageFormat.format(person, "1", "1", info.getInsuredEmail(),
		  partName[0], partName[1], info.getInsuredName(),
		  DateUtils.dateToString(info.getInsuredBirth(), "yyyyMMdd"),
		  info.getInsuredTel(), getGender(info.getInsuredGender()),
		  getCertificateType(info.getInsuredCredentialType()),
		  info.getInsuredCredentialNo());
	  partName = getPartName(info.getHolderName());
	  persons += MessageFormat.format(person, "2", "12",
		  info.getInsuredEmail(), partName[0], partName[1],
		  info.getHolderName(),
		  DateUtils.dateToString(info.getHolderBirth(), "yyyyMMdd"),
		  info.getInsuredTel(), getGender(info.getHolderGender()),
		  getCertificateType(info.getHolderCredentialType()),
		  info.getHolderCredentialNo());
	  ownerId = "2";
	}

	request = request.replace("##OWNERID##", ownerId);
	request = request.replace("##PERSON##", persons);

	try {
	  Svl_tansferPolicyDataServiceStub spds = new Svl_tansferPolicyDataServiceStub();
	  HttpTransportProperties.Authenticator basicAuth = new HttpTransportProperties.Authenticator();
	  basicAuth.setUsername("user1");
	  basicAuth.setPassword("pass1");
	  spds._getServiceClient().getOptions()
		  .setProperty(HTTPConstants.AUTHENTICATE, basicAuth);
	  logger.info("BDFZ_Approval_Request:" + request);

	  TansferpolicyData tansData = new TansferpolicyData();
	  tansData.setXmlData(request);
	  tansData.setName("user1");
	  TansferpolicyDataResponse res = spds.tansferpolicyData(tansData);
	  String response = res.getTansferpolicyDataReturn();
	  logger.info("BDFZ_Approval_Response:" + res.getTansferpolicyDataReturn()
		  + ":" + response);
	  if (response != "failure") {
		message.setInsNo(response);
		message.setInsTransNo(response);
		message.setMessage(response);
		message.setStatus(MsgStatusEnum.SUCCESS);
		message.setInsStatus(InsuranceStatusEnum.EFFECT);
	  } else {
		message.setStatus(MsgStatusEnum.FAIL);
	  }
	} catch (RemoteException e) {
	  // TODO Auto-generated catch block
	  e.printStackTrace();
	  message.setStatus(MsgStatusEnum.FAIL);
	}
	return message;
  }

  @Override
  public InsReturnMsg PolicyQuery(OrderItemInfo info) {
	// TODO Auto-generated method stub
	return null;
  }

  @Override
  public InsReturnMsg PolicyCancel(OrderItemInfo info) {
	// TODO Auto-generated method stub
	InsReturnMsg message = new InsReturnMsg();
	try {
	  Svl_tansferPolicyDataServiceStub spds = new Svl_tansferPolicyDataServiceStub();
	  HttpTransportProperties.Authenticator basicAuth = new HttpTransportProperties.Authenticator();
	  basicAuth.setUsername("user1");
	  basicAuth.setPassword("pass1");
	  spds._getServiceClient().getOptions()
		  .setProperty(HTTPConstants.AUTHENTICATE, basicAuth);
	  logger.info("BDFZ_Cancel_Request:" + info.getInsuranceNo());

	  CancelPolicy tansData = new CancelPolicy();
	  tansData.setPolicyNo(info.getInsuranceNo());
	  CancelPolicyResponse res;

	  res = spds.cancelPolicy(tansData);
	  String response = res.getCancelPolicyReturn();
	  logger.info("BDFZ_Cancel_Response:" + res.getCancelPolicyReturn() + ":"
		  + response);

	  if (response != null && !response.isEmpty() && response == "保单契撤成功") {
		message.setStatus(MsgStatusEnum.SUCCESS);
		message.setInsStatus(InsuranceStatusEnum.CANCELED);

	  } else {
		message.setStatus(MsgStatusEnum.FAIL);
		message.setInsStatus(InsuranceStatusEnum.INVALID);
		message.setMessage(response);
	  }
	} catch (RemoteException e) {
	  // TODO Auto-generated catch block
	  e.printStackTrace();
	  message.setStatus(MsgStatusEnum.FAIL);
	  message.setInsStatus(InsuranceStatusEnum.INVALID);
	}
	return message;
  }

  public String getProductCode() {
	return productCode;
  }

  public void setProductCode(String productCode) {
	this.productCode = productCode;
  }

  public BDFZConfigAir getBdfzConfigAir() {
	ConfigManagementAir config = new ConfigManagementAir(productCode);
	return config.getBDFZConfiguration();
  }

  public String getGender(String gender) {
	String strGender = "1";
	if (gender == "女") {
	  strGender = "2";
	}
	return strGender;
  }

  public String getCertificateType(String certificateType) {
	if (certificateType == "身份证") {
	  return "1";
	} else {
	  return "2";
	}
  }

  public String[] getPartName(String name) {
	String[] partName = new String[2];
	if (name.lastIndexOf(' ') > 0) {
	  partName[0] = name.substring(0, name.lastIndexOf(' '));
	  partName[1] = name.substring(name.lastIndexOf(' ') + 1);
	} else if (name.length() > 3) {
	  partName[0] = name.substring(0, 2);
	  partName[1] = name.substring(2);
	} else {
	  partName[0] = name.substring(0, 1);
	  partName[1] = name.substring(1);
	}
	return partName;
  }

}
